package com.samp.bblock.core.web.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.samp.bblock.core.exception.WebException;


public class JsonToFormParamsUtils {
	
	private Map<String, String[]> paramsList = new HashMap<String,String[]>();
	
	public Map<String, String[]> toHttpParams(Map<Object, Object> jsonMap) throws WebException{
		try{
			return _toHttpParams(jsonMap);
		}catch(Exception e){
			throw new WebException(new StringBuilder().append("Convert jsonMap[").append(jsonMap).append("] to http form params error.").append(e.getMessage()).toString());
		}
	}
	
	private Map<String, String[]> _toHttpParams(Map<Object, Object > jsonMap ){
		pmap(jsonMap, null);
		return this.paramsList;
	}
	
	private void pmap(Map<Object, Object> json, String prefix ){
		Iterator i = json.entrySet().iterator();
		while( i.hasNext() ){
			Map.Entry entry = (Map.Entry)i.next();
			Object k = entry.getKey().toString();
			Object v = entry.getValue();
			if( v != null ){
				if( v instanceof Collection ){
					pcollection((Collection)v,new StringBuilder().append(prefix == null ? "":new StringBuilder().append(prefix).append(".").toString()).append(k).toString());
				}else if( v instanceof Map ){
					pmap((Map)v, new StringBuilder().append(prefix == null ? "":new StringBuilder().append(prefix).append(".").toString()).append(k).toString());
				}else{
					this.paramsList.put(new StringBuilder().append(prefix == null ? "":new StringBuilder().append(prefix).append(".").toString()).append(k).toString(), new String[]{v.toString()});
				}
			}
		}
	}
	
	private void pcollection(Collection<?> json, String prefix){
		int i = 0 ;
		List<String> temp = null;
		for( Iterator  i$ = json.iterator(); i$.hasNext(); ){
			Object v = i$.next();
			if( v != null ){
				if( v instanceof Collection ){
					pcollection((Collection)v, new StringBuilder().append(prefix).append("[").append(i).append("]").toString());
					i++;
				}else if( v instanceof Map ){
					pmap((Map)v, new StringBuilder().append(prefix).append("[").append(i).append("]").toString());
					i++;
				}else{
					if( temp == null ){
						temp = new ArrayList();
					}
					temp.add(v.toString());
				}
			}
		}
		if( temp != null ){
			String[] tempArray = new String[temp.size()];
			this.paramsList.put(prefix, temp.toArray(tempArray));
		}
	}
	
}